package com.canbot.u05.activity.customvoice.tool;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.canbot.u05.R;
import com.canbot.u05.activity.customvoice.CustomDialogActivity;
import com.canbot.u05.activity.customvoice.bean.AnswerBean;
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas;
import com.canbot.u05.activity.customvoice.bean.QuestionBean;
import com.canbot.u05.utils.ToastTools;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * CustomDialogExcelLoader
 *
 * @author liu.heng
 * @date 2018/5/30
 */

public class CustomDialogExcelLoader extends AsyncTask<String, Void, ArrayList<CustomDialogExcelDatas>> {

        private static final String TAG = "CustomDialogExcelLoader";

        private Context context;

        private static final String AUDIO_PREFIX = "/uusound/";

        private static final String IMAGE_PREFIX = "/uupic/";

        private static Pattern SPACE_PATTERN = Pattern.compile("\\s*|\t|\r|\n");

        private static Pattern SYMBOLS_PATTERN = Pattern.compile("[`~!@#$^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥……& amp;*（）——+|{}【】‘；：”“’。，、？|-]");

        public CustomDialogExcelLoader(Context context) {
                this.context = context;
        }


        @Override
        protected ArrayList<CustomDialogExcelDatas> doInBackground(String... params) {
                return getXlsData(params[0], 0);
        }

        @Override
        protected void onPostExecute(ArrayList<CustomDialogExcelDatas> officeList) {

                if (officeList != null) {
                        final CustomDialogActivity a = (CustomDialogActivity) context;
                        a.updata(officeList);
                }
        }

        /**
         * 获取 excel 表格中的数据,不能在主线程中调用
         */
        private ArrayList<CustomDialogExcelDatas> getXlsData(String xlsName, int index) {

                final File file = new File(xlsName);
                if (!file.exists()) {
                        new Thread(new Runnable() {
                                private Handler handler = new Handler(Looper.getMainLooper());

                                @Override
                                public void run() {
                                        handler.post(new Runnable() {

                                                @Override
                                                public void run() {
                                                        //放在UI线程弹Toast
                                                        ToastTools.newInstance(context).showText(context.getString(R.string.wrong_file_format));
                                                }
                                        });
                                }
                        }).start();
                        return null;
                }

                final ArrayList<CustomDialogExcelDatas> beanList = new ArrayList();

                Workbook workbook = null;
                try {
                        workbook = Workbook.getWorkbook(new FileInputStream(file));
                }
                catch (IOException e) {
                        e.printStackTrace();
                }
                catch (BiffException e) {
                        e.printStackTrace();
                }
                if (workbook == null) {
                        return null;
                }
                final Sheet sheet = workbook.getSheet(index);

                final int sheetNum = workbook.getNumberOfSheets();
                final int sheetRows = sheet.getRows();
                final int sheetColumns = sheet.getColumns();

                Log.d(TAG, "the num of sheets is " + sheetNum);
                Log.d(TAG, "the name of sheet is  " + sheet.getName());
                Log.d(TAG, "total rows is 行=" + sheetRows);
                Log.d(TAG, "total cols is 列=" + sheetColumns);

                List<AnswerBean> answers = new ArrayList<>();

                List<QuestionBean> questions = new ArrayList<>();

                final int limitNum = 10001;
                if (sheetRows > limitNum) {
                        new Thread(new Runnable() {
                                private Handler handler = new Handler(Looper.getMainLooper());

                                @Override
                                public void run() {
                                        handler.post(new Runnable() {

                                                @Override
                                                public void run() {
                                                        //放在UI线程弹Toast
                                                        ToastTools.newInstance(context).showText(context.getString(R.string.more_rows_table_data));
                                                }
                                        });
                                }
                        }).start();
                        return null;
                }
                // "问题", "回答（TTS或音频名字）", "图片名字"
                for (int i = 1; i < sheetRows; i++) {

                        final AnswerBean bean1 = new AnswerBean();
                        bean1.setTtstext(sheet.getCell(1, i).getContents());
                        if (sheetColumns == 2) {
                                bean1.setImgpath(sheet.getCell(2, i).getContents());
                        }
                        bean1.setType(1);
                        answers.add(bean1);
                        if (!sheet.getCell(0, i + 1 == sheetRows ? i - answers.size() + 1 : i + 1).getContents().isEmpty()) {
                                final QuestionBean bean2 = new QuestionBean();
                                String question = replaceStr(sheet.getCell(0, i - answers.size() + 1).getContents());
                                bean2.setQuestion(question);
                                bean2.setType(1);
                                questions.add(bean2);
                                final CustomDialogExcelDatas judgeEntity = new CustomDialogExcelDatas();
                                Log.d(TAG, "total rows is 行=" + answers);
                                List<AnswerBean> answers1 = new ArrayList<>();
                                List<QuestionBean> questions1 = new ArrayList<>();
                                for (int j = 0; j < answers.size(); j++) {
                                        final AnswerBean bean3 = new AnswerBean();
                                        //判断图片行是否有内容
                                        if (sheetColumns == 2) {
                                                if (!answers.get(j).getImgpath().isEmpty()) {
                                                        bean3.setImgpath(IMAGE_PREFIX + answers.get(j).getImgpath());
                                                }
                                        }
                                        //判断回答内容是TTS还是音频
                                        if (answers.get(j).getTtstext().endsWith(".mp3") || answers.get(j).getTtstext().endsWith(".wav")) {
                                                bean3.setSoundpath(AUDIO_PREFIX + answers.get(j).getTtstext());
                                                bean3.setType(0);
                                        }
                                        else {
                                                bean3.setTtstext(answers.get(j).getTtstext());
                                                bean3.setType(1);
                                        }
                                        answers1.add(bean3);
                                }
                                for (int k = 0; k < questions.size(); k++) {
                                        final QuestionBean bean4 = new QuestionBean();
                                        bean4.setQuestion(questions.get(k).getQuestion());
                                        bean4.setType(1);
                                        questions1.add(bean4);
                                }
                                judgeEntity.setListAsBean(answers1);
                                judgeEntity.setListQsBean(questions1);
                                beanList.add(judgeEntity);
                                Log.e(TAG, beanList.size() + "&&" + beanList.get(0).getListQsBean() + "&&" + beanList.get(0).getListAsBean());
                                Log.e(TAG, beanList.size() + "&&" + beanList.get(0).getListQsBean() + "&&" + beanList.get(0).getListAsBean());
                                Log.e(TAG, judgeEntity.getListQsBean() + "&&" + judgeEntity.getListAsBean());
                                answers.clear();
                                questions.clear();
                        }
                }

                workbook.close();

                return beanList;
        }

        /**
         * 移除字符串中的特殊字符
         */
        private static String replaceStr(String str) {
                String question = "";
                if (str != null) {
                        Matcher m = SPACE_PATTERN.matcher(str);
                        question = m.replaceAll("");
                        Matcher q = SYMBOLS_PATTERN.matcher(question);
                        question = q.replaceAll("");
                }
                return question;
        }
}
